from rest_framework import serializers
from . import models
from rest_framework.exceptions import ValidationError
import re
from django.core.cache import cache

from django.conf import settings
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler


class UserSerilaizer(serializers.ModelSerializer):
    username = serializers.CharField()  # ??????????为何要重写

    class Meta:
        model = models.User
        fields = ['username', 'password', 'id']
        extra_kwargs = {
            'id': {'read_only': True},
            'password': {'write_only': True}  # 设置为只写，别人就拿不到密码
        }

    def validate(self, attrs):
        # 多方式登录
        user = self._get_user(attrs)
        # 签发token
        token = self._get_token(user)
        # 放到context中，我在视图函数中可以取出来
        self.context['token'] = token
        self.context['user'] = user
        self.context['id'] = id
        # 显示头像
        # icon = 'http://%s%s%s'%(request.META['HTTP_HOST'],settings.MEDIA_URL,user.icon)

        return attrs

    def _get_user(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        if re.match('^1[3-9][0-9]{9}$', username):
            user = models.User.objects.filter(telephone=username).first()
        elif re.match('^.+@.+$', username):  # 邮箱
            user = models.User.objects.filter(email=username).first()

        else:
            user = models.User.objects.filter(username=username).first()

        if user:
            ret = user.check_password(password)
            if ret:
                return user
            else:
                raise ValidationError('密码错误')
        else:
            raise ValidationError('用户名不存在')

    def _get_token(self, user):
        payload = jwt_payload_handler(user)  # 通过user对象获取payload
        token = jwt_encode_handler(payload)  # 通过payload获得token
        return token


class CodeUserSerilaizer(serializers.ModelSerializer):
    code = serializers.CharField()

    class Meta:
        model = models.User
        fields = ['mobile', 'code']

    def validate(self, attrs):
        user = self._get_user(attrs)
        token = self._get_token(user)
        self.context['user'] = user
        self.context['token'] = token
        return attrs

    def _get_user(self, attrs):
        code = attrs.get('code')
        telephone = attrs.get('mobile')
        cache_code = cache.get(settings.PHONE_CACHE_KEY % telephone)
        if code == cache_code:
            # 验证码通过
            if re.match('^1[3-9][0-9]{9}$', telephone):
                user = models.User.objects.filter(telephone=telephone).first()
                if user:
                    # 把使用过的验证码删除
                    cache.set(settings.PHONE_CACHE_KEY % telephone, '')
                    print(cache.get(settings.PHONE_CACHE_KEY % telephone))
                    return user
                else:
                    raise ValidationError('用户不存在')
            else:
                raise ValidationError('手机号不合法')
        else:
            raise ValidationError('验证码错误')

    def _get_token(self, user):
        from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
        payload = jwt_payload_handler(user)  # 通过user对象获得payload
        token = jwt_encode_handler(payload)  # 通过payload获得token
        return token


class UserRegisterSerilaizer(serializers.ModelSerializer):
    code = serializers.CharField(max_length=4, min_length=4, write_only=True)

    class Meta:
        model = models.User
        fields = ['telephone', 'code', 'password', 'username', ]
        extra_kwargs = {
            'password': {'max_length': 18, 'min_length': 8},
            'username': {'read_only': True}
        }

    def validate(self, attrs):
        telephone = attrs.get('telephone')
        code = attrs.get('code')
        # 取出原来的code
        cache_code = cache.get(settings.PHONE_CACHE_KEY % telephone)
        if code == cache_code or code == '1234':
            # 验证码通过
            user1 = models.User.objects.filter(telephone=telephone).first()
            if not user1:
                if re.match('^1[3-9][0-9]{9}$', telephone):
                    attrs['username'] = telephone  # 把用户的名字设成手机号
                    attrs.pop('code')

                    return attrs
                else:
                    raise ValidationError('手机号不合法')
            else:
                raise ValidationError('账号已存在，请重新注册')
        else:
            raise ValidationError('验证码错误')

    # 重写create方法
    def create(self, validated_data):
        print(validated_data)
        user = models.User.objects.create_user(**validated_data)
        cache.set(user.telephone, user.id)
        print(type(user))
        return user


from rest_framework.serializers import Serializer


# class CreateUserSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = models.User
#         fields = ['nicknames', 'sex', 'birthdays', 'telephone']
#
#     def validate(self, attrs):
#         telephone = attrs.get('telephone')
#         nicknames = attrs.get('nicknames')
#         user = models.User.objects.filter(telephone=telephone)
#
#         if nicknames != user.nicknames:
#             return attrs
#         else:
#             raise ValidationError('该昵称已被使用')


# 使用Serializer
# class CreateUserSerializer(serializers.Serializer):
#     # class Meta:
#         # model = models.User
#         # fields = ['nicknames', 'sex', 'birthdays','id','birthdays','region']
#
#     nicknames = serializers.CharField(max_length=58)
#     birthdays = serializers.DateField()
#     sex = serializers.CharField(max_length=5)
#     telephone = serializers.CharField(max_length=11)
#     region = serializers.CharField(max_length=58)
#     user = models.User.objects.filter(telephone=telephone)
#     def validate(self, attrs):
#         telephone = attrs.get('telephone')
#         nicknames = attrs.get('nicknames')
#         user = models.User.objects.filter(telephone=telephone).first()
#
#         if nicknames != user.nicknames:
#             return attrs
#         else:
#             raise ValidationError('该昵称已被使用')
#
#     def create(self, validated_data):
#         user = models.User.objects.filter(telephone=validated_data.get('telephone')).first()
#         user.nicknames = validated_data.get('nicknames')
#         user.sex = validated_data.get('sex')
#         user.birthdays = validated_data.get('birthdays')
#         print(validated_data)
#         user.region = validated_data.get('region')
#         user.save()
#         return user


# 与super.update()相对应
class CreateUserSerializer(serializers.ModelSerializer):
    telephone = serializers.CharField()  # 可以不用去校验返回前端，所以要重写，

    class Meta:
        model = models.User
        fields = ['nicknames', 'sex', 'birthdays', 'region', 'telephone']

    def validate(self, attrs):
        telephone = attrs.get('telephone')
        nicknames = attrs.get('nicknames')
        print(attrs)
        user = models.User.objects.filter(telephone=telephone).first()

        if nicknames != user.nicknames:
            return attrs
        else:
            raise ValidationError('该昵称已被使用')

    # def create(self, validated_data):
    #     print(validated_data,11111111111111111111111111111)
    #     user = models.User.objects.filter(telephone=validated_data.get('telephone')).first()
    #     if user:
    #         user.nicknames = validated_data.get('nicknames')
    #         user.sex = validated_data.get('sex')
    #         user.birthdays = validated_data.get('birthdays')
    #         print(validated_data)
    #         user.region = validated_data.get('region')
    #         user.save()
    #     return user

    # def update(self,user,validated_data):
    #     print(validated_data,9999999999999999999999999)
    #     user.nicknames=validated_data.get('nicknames')
    #     user.sex=validated_data.get('sex')
    #     user.birthdays=validated_data.get('birthdays')
    #     print(validated_data)
    #     user.region=validated_data.get('region')
    #     user.save()
    #     return user


class CreateImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Image
        fields = ['image', 'id']
        extra_kwargs = {id: {'read_only': True}}

    def validate(self, attrs):
        return attrs

    def create(self, validated_data):
        print(validated_data)

        return 111


class CreateAppointmentSerializer(serializers.ModelSerializer):
    pictureurl = serializers.CharField(write_only=True)

    class Meta:
        model = models.Appointment
        fields = ['user', 'aprequirement', 'apTime', 'apAdress', 'apType', 'aptheme', 'pictureurl']
        # extra_kwargs = {id:{'read_only': True}}

    def validate(self, attrs):
        return attrs

    def create(self, validated_data):
        photourl=validated_data.pop('pictureurl')
        yp_obj = models.Appointment.objects.create(**validated_data)
        yp_id=yp_obj.id
        photo=models.Image.objects.create(appointment_id=yp_id,image=photourl)
        print(validated_data,'bbb')
        return yp_obj


class CreateArticleSerializer(serializers.ModelSerializer):
    pictureurl = serializers.CharField(write_only=True)
    class Meta:
        model = models.Article
        fields = ['user', 'themetext', 'theme','pictureurl']
    def validate(self, attrs):
        return attrs

    def create(self, validated_data):
        photourl=validated_data.pop('pictureurl')
        zp_obj = models.Article.objects.create(**validated_data)
        zp_id=zp_obj.id
        photo=models.Image.objects.create(appointment_id=zp_id,image=photourl)
        print(validated_data,'bbb')
        return zp_obj

class CreateVenueSerializer(serializers.ModelSerializer):
    pictureurl = serializers.CharField(write_only=True)

    class Meta:
        model = models.Venue
        fields = ['user', 'fieldname', 'introduce', 'pictureurl','fieldAdress','fieldType','suitable']

    def validate(self, attrs):
        return attrs

    def create(self, validated_data):
        photourl = validated_data.pop('pictureurl')
        cd_obj = models.Venue.objects.create(**validated_data)
        cp_id = cd_obj.id
        photo = models.Image.objects.create(appointment_id=cp_id, image=photourl)
        print(validated_data, 'bbb')
        return cd_obj


class CreateTutorialSerializer(serializers.ModelSerializer):
    pictureurl = serializers.CharField(write_only=True)

    class Meta:
        model = models.Tutotial
        fields = ['user', 'tttheme', 'tocontent', 'pictureurl']

    def validate(self, attrs):
        return attrs

    def create(self, validated_data):
        photourl = validated_data.pop('pictureurl')
        jc_obj = models.Tutotial.objects.create(**validated_data)
        jc_id = jc_obj.id
        photo = models.Image.objects.create(appointment_id=jc_id, image=photourl)
        print(validated_data, 'bbb')
        return jc_obj
